package dao

import (
	"log"

	"gitee.com/Yu-eng/Myproject/my-go-blog/models"
)

func GetPostPage(page, pageSize int) ([]models.Post, error) {
	page = (page - 1) * pageSize
	//这里的page是从 那里开始查 查多少个 还是pagesize
	//注意limit 的用法
	rows, err := DB.Query("select * from blog_post limit ?,?", page, pageSize)
	if err != nil {
		log.Println("post querry 出错 :", err)
		return nil, err
	}
	var posts []models.Post
	for rows.Next() {
		var post models.Post
		err = rows.Scan(&post.Pid,
			&post.Title,
			&post.Content,
			&post.Markdown,
			&post.CategoryId,
			&post.UserId,
			&post.ViewCount,
			&post.Type,
			&post.Slug,
			&post.CreateAt,
			&post.UpdateAt)
		if err != nil {
			log.Println("post rows.Scan 出错！ ：", err)
			return nil, err
		}
		posts = append(posts, post)
	}
	return posts, nil
}

func CountGetAllPost() (count int) {
	rows := DB.QueryRow("select count(1) from blog_post")
	err := rows.Scan(&count)
	if err != nil {
		log.Println("CountGetAllPost error ", err)
	}
	return
}

func GetPostPageByCategoryId(cid, page, pageSize int) ([]models.Post, error) {
	page = (page - 1) * pageSize
	//这里的page是从 那里开始查 查多少个 还是pagesize
	//注意limit 的用法
	rows, err := DB.Query("select * from blog_post where category_id = ? limit ?,?", cid, page, pageSize)
	if err != nil {
		log.Println("post querry 出错 :", err)
		return nil, err
	}
	var posts []models.Post
	for rows.Next() {
		var post models.Post
		err = rows.Scan(&post.Pid,
			&post.Title,
			&post.Content,
			&post.Markdown,
			&post.CategoryId,
			&post.UserId,
			&post.ViewCount,
			&post.Type,
			&post.Slug,
			&post.CreateAt,
			&post.UpdateAt)
		if err != nil {
			log.Println("post rows.Scan 出错！ ：", err)
			return nil, err
		}
		posts = append(posts, post)
	}
	return posts, nil
}

func CountGetAllPostByCategoryId(cId int) (count int) {
	rows := DB.QueryRow("select count(1) from blog_post where category_id = ?", cId)
	err := rows.Scan(&count)
	if err != nil {
		log.Println("CountGetAllPost error ", err)
	}
	return
}

//根据 pid  获得post信息
func GetPostById(pid int) models.Post {
	row, err := DB.QueryRow("select * from blog_post where pid = ?", pid)
	if err != nil {
		log.Println("post querry 出错 :", err)
		return nil, err
	}
	var posts []models.Post
	rows.Next()
	var post models.Post
	err = rows.Scan(&post.Pid,
		&post.Title,
		&post.Content,
		&post.Markdown,
		&post.CategoryId,
		&post.UserId,
		&post.ViewCount,
		&post.Type,
		&post.Slug,
		&post.CreateAt,
		&post.UpdateAt)
	if err != nil {
		log.Println("post rows.Scan 出错！ ：", err)
		return nil, err
	}
}
